import React, { createRef, forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import styled from 'styled-components';
import gsap from 'gsap'

/**
 * 两种模式
 * 1. 受控
 * 2. 非受控
 */

export type IFlopValue = number | string |undefined;

export interface IFlopNum2Props {
  value?:IFlopValue;
  defaultValue?:IFlopValue;
}

export interface IFlopNumActionRef{
  setValue:(value:IFlopValue)=>void;
  getValue:()=>number
}

export const useFlopNum2 = ()=>{
  const flopNumAction= createRef<IFlopNumActionRef>();

  return {
    flopNumAction
  }
}


const FlopNum2Wrap = styled.div`
width:100%;
height:100%;
color:#fff;
text-align:center;
font-size:20px;
`


export const  FlopNum2 = forwardRef<IFlopNumActionRef ,IFlopNum2Props>((props,ref)=>{
  const {value,defaultValue} = props;
  const [renderValue,setRenderValue] = useState(value===undefined ? defaultValue:value)
  const targetValueRef = useRef(value===undefined ? defaultValue:value)
  const renderValueRef = useRef(value===undefined ? defaultValue:value)

  const _setValue= (value:IFlopValue)=>{
    if(targetValueRef.current === value){
      return false;

    }
    targetValueRef.current = parseInt(String(value||'0'));
    setRenderValue(value)
    gsap.to(renderValueRef,{
      current: value,
      duration:0.5,
      // repeat:1,
      

      onUpdate:()=>{
        const newVal = renderValueRef.current?.toString().split('.')[0];
        console.log(newVal,'newVal');
        setRenderValue(newVal)

      }
    },)
  }
  const _getValue= ()=>{
    return targetValueRef.current as number;
  }

  useImperativeHandle(ref,()=>{
    return {
      setValue:_setValue,
      getValue:_getValue
    }
  })

  useEffect(()=>{
    _setValue(value)
  },[value])

  return (
    <FlopNum2Wrap >
      {renderValue}
    </FlopNum2Wrap>
  );
})
